package com.hhh.Controller;

import com.hhh.ExceptionHandle.CategoryException;
import com.hhh.Pojo.Category;
import com.hhh.Pojo.Result;
import com.hhh.Service.CategoryService;
import com.hhh.Service.DishService;
import com.hhh.Service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    SetmealService setmealService;

    @Autowired
    DishService dishService;

    //    查询菜品和套餐分类
//    查询菜品和套餐分类
//    查询菜品和套餐分类
    @GetMapping("/page")
    public Result SelectAll(long page, long pageSize) {
        log.info("查询套餐菜系分类");
        return Result.success(categoryService.SelectALL(page, pageSize));
    }

    //    加入菜品或套餐
//    加入菜品或套餐
//    加入菜品或套餐
    @PostMapping()
    public Result Insert(@RequestBody Category category) {
        log.info("加入菜品或套餐");
        Integer num = categoryService.Insert(category);
        if (num != 1)
            return Result.error("添加失败");
        else
            return Result.success(num);
    }

    //    修改菜品或套餐分类的信息
//    修改菜品或套餐分类的信息
//    修改菜品或套餐分类的信息
    @PutMapping()
    public Result Update(@RequestBody Category category) {
        log.info("修改菜品或套餐分类");
        Integer num = categoryService.Update(category);
        if (num != 1)
            return Result.error("修改失败");
        else
            return Result.success(num);
    }


    //    删除分类
    @DeleteMapping()
    public Result Delete(long ids) {
        log.info("删除分类");
        long dish = 0, setmeal = 0;
        Category category = categoryService.SelectById(ids);
//        检查是否关联了套餐
        if (category.getType() != 1) {
            setmeal = setmealService.SelectCount(category.getId());
        } else {
//         检查是否关联了菜品
            dish = dishService.SelectCount(category.getId());
        }
//        无关联，删除
        if (dish == 0 && setmeal == 0) {
            return Result.success(" 删除分类成功");
        } else
            throw new CategoryException("关联了套餐或者菜品,无法删除");
    }

    @GetMapping("/list")
    public Result SelectType(Category category) {
        log.info("根据类型查询分类");
        return Result.success(categoryService.SelectType(category));
    }
}
